package com.thh.filesystem.uitl;


import com.thh.filesystem.domain.response.FileSystemCode;
import com.thh.filesystem.exception.ExceptionCast;
import org.csource.fastdfs.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件系统 上传 下载  删除 类
 *
 * 采用的是  application.yml注入的方式
 */
@Component
public class FastDFSClient {


    @Value("${thh.fastdfs.tracker_servers}")
    String tracker_servers;
    @Value("${thh.fastdfs.connect_timeout_in_seconds}")
    int connect_timeout_in_seconds;
    @Value("${thh.fastdfs.network_timeout_in_seconds}")
    int network_timeout_in_seconds;
    @Value("${thh.fastdfs.charset}")
    String charset;




    //返回文件后缀
    public static String getPostfix(MultipartFile file) {
        try {
            if (!file.isEmpty()) {
                int begin = file.getOriginalFilename().lastIndexOf(".");
                int last = file.getOriginalFilename().length();
                String a = file.getOriginalFilename().substring(begin+1, last);
                return a;
            }
        } catch (Exception e) {

        }
        return "";
    }


    //上传文件到fastDFS

    /**
     *
     * @param multipartFile 文件
     * @return 文件id
     */
    public  String fdfsUpload(MultipartFile multipartFile){
        //初始化fastDFS的环境
        initFdfsConfig();
        //创建trackerClient
        TrackerClient trackerClient = new TrackerClient();
        try {
            TrackerServer trackerServer = trackerClient.getConnection();
            //得到storage服务器

            StorageServer storeStorage = trackerClient.getStoreStorage(trackerServer);
            //创建storageClient来上传文件
            StorageClient1 storageClient1 = new StorageClient1(trackerServer,storeStorage);


            StorageClient storageClient = new StorageClient(trackerServer,storeStorage);
            //上传文件
            //得到文件字节
            byte[] bytes = multipartFile.getBytes();
            //得到文件的原始名称
            String originalFilename = multipartFile.getOriginalFilename();
            //得到文件扩展名
            String ext = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            String fileId = storageClient1.upload_file1(bytes, ext, null);

            return fileId;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //初始化fastDFS环境
    private void initFdfsConfig(){
        //初始化tracker服务地址（多个tracker中间以半角逗号分隔）
        try {
            ClientGlobal.initByTrackers(tracker_servers);
            ClientGlobal.setG_charset(charset);
            ClientGlobal.setG_network_timeout(network_timeout_in_seconds);
            ClientGlobal.setG_connect_timeout(connect_timeout_in_seconds);
        } catch (Exception e) {
            e.printStackTrace();
            //抛出异常
            ExceptionCast.cast(FileSystemCode.FS_INITFDFSERROR);
        }
    }



}
